import 'package:aliplayer_widget/aliplayer_widget_lib.dart';
import 'package:aliplayer_widget/base/safe_value_notifier.dart';
import 'package:flutter/material.dart';
import 'package:hktk_app/dao/course_dao.dart';
import 'package:hktk_app/dao/industry_dao.dart';
import 'package:hktk_app/model/course/video_info_model.dart';
import 'package:hktk_app/util/event_bus_util.dart';

/// 视频切换回调方法
typedef VideoSwitchIngFun = void Function({
  required VideoInfoModel infoModel,
  required String chapterId,
  required String chapterName,
});

// /// 视频清晰度含义
// final Map<String, String> _clarityMap = {
//   "FD": "FD 流畅",
//   "LD": "LD 标清",
//   "SD": "SD 高清",
//   "HD": "HD 超清",
//   "OD": "OD 原画",
//   "2K": "2K",
//   "4k": "4k",
//   "AUTO": "自适应",
// };

// 视频保存按考试创建目录保存
class CourseVideoPage1 extends StatefulWidget {
  final String columnId;

  /// 科目id
  final String topChapterId;

  /// 视频id
  final String videoId;

  /// 阿里云视频id
  final String aliyunVideoId;

  /// 是否横屏，true：横屏，false：竖屏
  final bool isHorizontal;

  /// 视频标题
  final String videoTitle;

  /// 视频观看时长
  final int watchDuration;

  /// 视频切换回调方法
  final VideoSwitchIngFun? videoSwitchIngFun;

  bool isFinished;

  CourseVideoPage1({
    super.key,
    required this.columnId,
    required this.topChapterId,
    required this.videoId,
    required this.aliyunVideoId,
    required this.isHorizontal,
    required this.videoTitle,
    required this.watchDuration,
    // required this.videoSwitchIngFun,
    this.videoSwitchIngFun,
    this.isFinished = false,
  });

  @override
  State<CourseVideoPage1> createState() => CourseVideoPageState();
}

class CourseVideoPageState extends State<CourseVideoPage1> {
  late SafeValueNotifier<int>? _playStateNotifier;
  late AliPlayerWidgetController _controller;
  late bool _isLoading = true;

  // late VoidCallback? tiListener;
  // late VoidCallback? totalListener;

  void pausePlayer() {
    _controller.pause();
  }

  void playPlayer() {
    _controller.play();
  }

  int getPlayState() {
    return _controller.playStateNotifier.value;
  }

  int getTi() {
    return _controller.currentPositionNotifier.value.inMilliseconds;
  }

  int getTotal() {
    return _controller.totalDurationNotifier.value.inMilliseconds;
  }

  // 暴露一个切换播放源的方法
  Future<void> switchSource(EventCourseDetailVideoSwitch event) async {
    // 在切换数据源前，应该先移除旧的监听器
    // if(tiListener!=null){
    //   _controller.currentPositionNotifier.removeListener(tiListener!);
    // }
    // if(totalListener!=null){
    //   _controller.totalDurationNotifier.removeListener(totalListener!);
    // }

    return CourseDao.aliyunAuth(
            topChapterId: event.chapterId,
            columnId: widget.columnId,
            videoId: event.infoModel.aliyunVideoId!)
        .then((res) {
      _controller
          .seek(Duration(milliseconds: event.infoModel.watchDuration ?? 0));

      // final data = AliPlayerWidgetData(
      //   videoUrl: "https://outin-4f3dc9653abb11f085a700163e1c8dba.oss-cn-shanghai.aliyuncs.com/sv/d95cb6e-198a279e33f/d95cb6e-198a279e33f.mp4?Expires=1755076715&OSSAccessKeyId=LTAI8bKSZ6dKjf44&Signature=97rX%2FXW3cDGVe1IDwdLJWxEGVB0%3D",
      //   // coverUrl: "http://outin-4f3dc9653abb11f085a700163e1c8dba.oss-cn-shanghai.aliyuncs.com/b087cecc781c71f08a485017f0f90102/snapshots/a145e4e9326b4df9be2936eb14062112-00001.jpg?Expires=1755076632&OSSAccessKeyId=LTAI8bKSZ6dKjf44&Signature=E2Qp%2FqRVUDX%2BTAYsQEqIyDAeNG8%3D",
      //   videoTitle: "Sample Video Title",
      // );
      _controller.configure(
        AliPlayerWidgetData(
          videoSource: VideoSourceFactory.createVidAuthSource(
            vid: event.infoModel.aliyunVideoId!,
            // playAuth: res,
            // vid: "b087cecc781c71f08a485017f0f90102",
            playAuth: res,
          ),
          videoTitle: event.chapterName,
        ),
      );
      // _controller.scaleModeNotifier

      // tiListener=(value) {
      //   if(mounted){
      //     // 监听播放进度
      //     // Duration d = value;
      //     // d.inMilliseconds;
      //     ti = value.inMilliseconds;
      //   }
      // } as VoidCallback;
      // _controller.currentPositionNotifier.addListener(tiListener!);
      // totalListener=(value) {
      //   if(mounted){
      //     // 监听视频时长
      //     total = value.inMilliseconds;
      //   }
      // } as VoidCallback;
      // _controller.totalDurationNotifier.addListener(totalListener!);
    });
  }

  @override
  void initState() {
    //   initState
    super.initState();
    // 只需要证书，播放凭证不需要
    _controller = AliPlayerWidgetController(context);
    //   获取播放凭证
    CourseDao.aliyunAuth(
            topChapterId: widget.topChapterId,
            columnId: widget.columnId,
            videoId: widget.aliyunVideoId)
        .then((res) {
      final data = AliPlayerWidgetData(
        videoSource: VideoSourceFactory.createVidAuthSource(
          vid: widget.aliyunVideoId,
          playAuth: res,
        ),
        videoTitle: widget.videoTitle,
      );
      // 设置指定播放位置
      _controller.seek(Duration(milliseconds: widget.watchDuration));
      _controller.configure(data); // 设置自动播放

      // _controller.videoSizeNotifier.addListener((){
      //   //640,360
      //   _controller.videoSizeNotifier.value;
      //   debugPrint("");
      // });

      // tiListener=(value) {
      //   if(mounted){
      //     // 监听播放进度
      //     // Duration d = value;
      //     // d.inMilliseconds;
      //     ti = value.inMilliseconds;
      //   }
      //
      // } as VoidCallback;
      // _controller.currentPositionNotifier.value;
      // _controller.currentPositionNotifier.addListener(tiListener!);
      // totalListener=(value) {
      //   if(mounted){
      //     // 监听视频时长
      //     total = value.inMilliseconds;
      //   }
      //
      // } as VoidCallback;
      // _controller.totalDurationNotifier.addListener(totalListener!);

      // todo 监听播放状态
      _playStateNotifier = _controller.playStateNotifier;
      _playStateNotifier!.addListener(listener);
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
      }
    }).catchError((err) {
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
      }
    });
  }

  void listener() {
    if (mounted) {
      if (_controller.playStateNotifier.value == FlutterAvpdef.completion) {
        // 跨层级传递，广播
        eventBus.fire(PlayerEvent(
          videoId: widget.videoId,
          playState: FlutterAvpdef.completion,
          position: 100,
          duration: 0,
        ));
      }

      // 监听播放状态
      // print("播放状态：${_controller.playStateNotifier.value}");
      // print("播放进度：${_controller.currentPositionNotifier.value}");
      // print("视频时长：${_controller.totalDurationNotifier.value}");
      // print("播放速度：${_controller.playbackRateNotifier.value}");
      // print()
    }
  }

  @override
  void dispose() {
    //   dispose
    super.dispose();
    
    _controller.destroy();
    _playStateNotifier?.removeListener(listener);
  }

  @override
  Widget build(BuildContext context) {
    // 
    if (_isLoading) {
      return Center(child: CircularProgressIndicator());
    } else {
      return AliPlayerWidget(_controller,
          examId: IndustryDao.getExamKey().examId,
          overlays: [
            Positioned(
              top: 5,
              right: 5,
              // cdn/huikao/png/202502/20250215112138605@shuiyin.png
              child: Image.asset(
                "images/login/20250215112138605@shuiyin.png",
                width: 60,
              ),
            )
          ]);
    }
  }
}
